package com.example.app2;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;


import com.example.app2.util.FileUtil;

import java.io.File;

public class FileWriteActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_name;
    private EditText et_age;
    private EditText et_height;
    private EditText et_weight;
    private CheckBox ckb_married;
    private String path;
    private TextView tv_txt;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_writefile);
        et_name = findViewById(R.id.et_name);
        et_age = findViewById(R.id.et_age);
        et_height = findViewById(R.id.et_height);
        et_weight = findViewById(R.id.et_weight);
        ckb_married = findViewById(R.id.ckb_married);
        tv_txt = findViewById(R.id.tv_show);
        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_load).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_save:
                String name=et_name.getText().toString();
                String age=et_age.getText().toString();
                String height=et_height.getText().toString();
                String weight=et_height.getText().toString();

                StringBuilder sb=new StringBuilder();
                sb.append("name:"+name);
                sb.append("\nage:"+age);
                sb.append("\nheight:"+height);
                sb.append("\nweight:"+weight);
                sb.append("\nmarried:"+(ckb_married.isChecked()?"true":"false"));
                String directory=null;
                //存储到外部存储的私有空间
                //directory= getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS.toString()).toString();
                //外部存储的公共空间
                //directory=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
                //内部存储的私有空间
                directory=getFilesDir().toString();
                String filename=System.currentTimeMillis()+".txt";
                path = directory+ File.separatorChar+filename;
                FileUtil.saveText(path,sb.toString());
                Toast.makeText(this, "保存成功："+path, Toast.LENGTH_SHORT).show();
                Log.d("tang", path);
                break;
            case R.id.btn_load:
                tv_txt.setText(FileUtil.loadText(path));
                break;
        }
    }
}
